package com.example.wexcle.demos.web.config;

import java.util.AbstractList;
import java.util.List;

/**
 * 同ListPartitioner是一个作用，将大量数据分批处理
 */
public class ListUtils {
    public static <T> List<List<T>> partition(final List<T> list, final int size) {
        if (list == null) {
            throw new NullPointerException("List must not be null");
        }
        if (size <= 0) {
            throw new IllegalArgumentException("Size must be greater than 0");
        }
        return new Partition<>(list, size);
    }
    private static class Partition<T> extends AbstractList<List<T>> {
        private final List<T> list;
        private final int size;
        /**
         * @param list 传入的列表
         * @param size 指定的长度，每size个数据切割为一个子列表
         */
        private Partition(final List<T> list, final int size) {
            this.list = list;
            this.size = size;
        }

        /**
         * 获取按指定长度拆分后，索引位置的子列表
         * @param index
         * @return
         */
        @Override
        public List<T> get(final int index) {
            //获取拆分后子列表的个数
            final int listSize = size();
            if (index < 0) {
                throw new IndexOutOfBoundsException("Index " + index + " must not be negative");
            }
            if (index >= listSize) {
                throw new IndexOutOfBoundsException("Index " + index + " must be less than size " +
                        listSize);
            }
            final int start = index * size;
            final int end = Math.min(start + size, list.size());
            //返回子列表
            return list.subList(start, end);
        }
        @Override
        public int size() {
            //（传入列表总长度/指定的长度）向上取整，即为拆分后子列表的个数
            return (int) Math.ceil((double) list.size() / (double) size);
        }
        @Override
        public boolean isEmpty() {
            return list.isEmpty();
        }
    }
}

